<?php 
global $_GPC, $_W;
$shopid=check_right(2);
if(!$shopid)message("请先选择需要管理的店铺",$this->createWebUrl('shop'),'error');
$shop=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_group')." WHERE weid = '{$_W['uniacid']}' and id='".$shopid."'");
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
$cfg = $this->module['config'];

if($operation=="display" || $operation=="charge"){
	$userlist = pdo_fetchall("SELECT id,realname FROM ".tablename('j_hmoney_user') . " WHERE weid = '{$_W['uniacid']}' and pcate='".$shopid."' order by id desc");
	$userary = array();
	foreach ($userlist as $row) {
		$userary[$row['id']]=$row['realname'];
	}
} elseif ($operation == 'salepage') {
	$pindex = max(1, intval($_GPC['page']));
	$psize = 10;
	$condition = " and a.groupid ='".$shopid."' ";
	switch(intval($_GPC['datetype'])){
		case "1":
			$condition .= " and a.createdate='".date('Y-m-d')."' ";
		break;
		case "2":
			$condition .= " and a.createdate='".date('Y-m-d',strtotime("-1 day"))."' ";
		break;
		case "3":
			$condition .= " and a.createdate>='".date('Y-m-d',strtotime("-6 day"))."' ";
		break;
		case "4":
			$condition .= " and a.createtime>='".strtotime($_GPC['statrtime'])."' and a.createtime<='".strtotime($_GPC['endtime'])."' ";
		break;
	}
	if(isset($_GPC['paytype']))$condition .= " and a.paytype = '" . $_GPC['paytype'] . "' ";
    if($_GPC['keyword']){
        if($_GPC['keytype']==2){
            $condition.="  and a.memberno in (SELECT id from ".tablename('j_hmoney_membercard')." where weid='{$_W['uniacid']}' and (cardno like '%".$_GPC['keyword']."%' or wxcardno like '%".$_GPC['keyword']."%' or realname like '%".$_GPC['keyword']."%'))";
        }else{
            $condition .= " and (a.out_trade_no='".$_GPC['keyword']."') ";
        }
    }
    $sql="SELECT a.*,b.realname,b.cardno,b.wxcardno FROM " . tablename('j_hmoney_order') . " a left join  " . tablename('j_hmoney_membercard') . " b on a.memberno=b.id WHERE a.weid='{$_W['uniacid']}' $condition order by a.id desc  LIMIT " . ($pindex - 1) * $psize . ',' . $psize;
	$list = pdo_fetchall($sql);
    $condition=str_replace("a.","",$condition);
	$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('j_hmoney_order') . " WHERE weid='{$_W['uniacid']}' $condition ");
	/**/
	$items = pdo_fetch('SELECT COUNT(*) as num1,sum(order_fee) as fee1,sum(discount_fee) as fee2,sum(total_fee-refund_fee) as fee3,sum(num) as num2 FROM '.tablename('j_hmoney_order')." WHERE weid='{$_W['uniacid']}' $condition  and ispay=1 and status<4 and refundstatus<2");

	$paytypeList1 = pdo_fetchall('SELECT paytype,COUNT(*) as num1,sum(paid_fee1) as fee1 FROM '.tablename('j_hmoney_order')." WHERE weid='{$_W['uniacid']}' $condition  and ispay=1  group by paytype ");

	$paytypeList2 = pdo_fetchall('SELECT paytype2,COUNT(*) as num1,sum(paid_fee2) as fee1 FROM '.tablename('j_hmoney_order')." WHERE weid='{$_W['uniacid']}' $condition  and ispay=1 and paytype2>-1  group by paytype2 ");

	$paytypeList=array();
	$temp=_getPaytpye("",$shopid);
	foreach($paytypeList1 as $row){
		$paytypeList[$row["paytype"]]=array(
			"str"=>$temp[$row["paytype"]],
			"num"=>$row["num1"],
			"fee1"=>$row["fee1"],
		);
	}

	foreach($paytypeList2 as $row){
		if(!isset($paytypeList[$row["paytype2"]]))$paytypeList[$row["paytype2"]]=array("str"=>$temp[$row["paytype2"]],"num"=>0,"fee1"=>0);
		$paytypeList[$row["paytype2"]]["num"]=$paytypeList[$row["paytype2"]]["num"]+$row["num1"];
		$paytypeList[$row["paytype2"]]["fee1"]=$paytypeList[$row["paytype2"]]["fee1"]+$row["fee1"];
	}
    /*退款部分*/
    $refundorder = pdo_fetch('SELECT COUNT(*) as num1,sum(num) as num2,sum(fee) as fee1 FROM ' . tablename('j_hmoney_refund') . " WHERE weid='{$_W['uniacid']}' $condition  and status=1 and rtype=1 ");
    $refundorder["num2"]=$refundorder["num2"]==null? 0 : $refundorder["num2"];
    $refundorder["fee1"]=$refundorder["fee1"]==null? 0 : $refundorder["fee1"];
    $refundgoods = pdo_fetch('SELECT sum(num) as num1,sum(fee) as fee1 FROM ' . tablename('j_hmoney_refund') . " WHERE weid='{$_W['uniacid']}' $condition  and status=1 and rtype=2 ");
    $refundgoods["num1"]=$refundgoods["num1"]==null? 0 : $refundgoods["num1"];
    $refundgoods["fee1"]=$refundgoods["fee1"]==null? 0 : $refundgoods["fee1"];
    $refundary = pdo_fetchall("SELECT paytype,sum(fee) as fee1 FROM " . tablename('j_hmoney_refund') . " WHERE weid='{$_W['uniacid']}' $condition and status=1 group by paytype ");
    $refundlist=array();
    foreach ($refundary as $row) {
        if(!isset($paytypeList[$row["paytype"]]))$paytypeList[$row["paytype"]]=array("str"=>$temp[$row["paytype"]],"num"=>0,"fee1"=>0);
        $paytypeList[$row["paytype"]]["fee1"]=$paytypeList[$row["paytype"]]["fee1"]-$row["fee1"];
    }


    die(json_encode(array("success"=>true,"list"=>$list,"pageall"=>$pageall,"total"=>$total,"sumfee"=>$items,"refundorder"=>$refundorder,"refundgoods"=>$refundgoods,"paylist"=>$paytypeList,"a"=>$sql)));
	
} elseif ($operation == 'getorderdetail') {
	$id=intval($_GPC['id']);
	$list = pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_ordergoods') . " WHERE weid = '{$_W['uniacid']}' and orderid='".$id."' order by id asc");
	die(json_encode(array("success"=>true,"list"=>$list)));
	
} elseif ($operation == 'getcharge') {
	$pindex = max(1, intval($_GPC['page']));
	$psize = 10;
	$condition = " and a.groupid ='".$shopid."' ";
	switch(intval($_GPC['datetype'])){
		case "1":
			$condition .= " and a.createdate='".date('Y-m-d')."' ";
		break;
		case "2":
			$condition .= " and a.createdate='".date('Y-m-d',strtotime("-1 day"))."' ";
		break;
		case "3":
			$condition .= " and a.createdate>='".date('Y-m-d',strtotime("-6 day"))."' ";
		break;
		case "4":
			$condition .= " and a.createtime>='".strtotime($_GPC['statrtime'])."' and a.createtime<='".strtotime($_GPC['endtime'])."' ";
		break;
	}
	if($_GPC['keyword']){
		$mid = pdo_fetchcolumn('SELECT id FROM '.tablename('j_hmoney_membercard')."  WHERE weid='{$_W['uniacid']}' and cardno='".$_GPC['keyword']."' limit 1");
		$condition .= " and (a.cid='".$mid."') ";
	}
	if(isset($_GPC['paytype']))$condition .= " and paytype = '" . $_GPC['paytype'] . "' ";
	$sql="SELECT a.*,b.cardno,b.realname FROM " . tablename('j_hmoney_recharge') . " a left join ".tablename('j_hmoney_membercard')." b on a.cid=b.id WHERE a.weid='{$_W['uniacid']}' $condition order by a.id desc  LIMIT " . ($pindex - 1) * $psize . ',' . $psize;
	$list = pdo_fetchall($sql);
	$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('j_hmoney_recharge') . " a WHERE weid='{$_W['uniacid']}' $condition ");
	$pageall= $total <= $psize ? 1 : $total % $psize ? ($total / $psize)+1 : $total / $psize;
    if($pindex==1){
        $condition=str_replace("a.","",$condition);
        $chargeitems = pdo_fetch('SELECT COUNT(*) as num1,sum(cash) as fee1,sum(gift) as fee2 FROM '.tablename('j_hmoney_recharge')." WHERE weid='{$_W['uniacid']}' $condition  and status=1 and usetype=0 ");
        $chargesale = pdo_fetch('SELECT COUNT(*) as num1,sum(cash) as fee1 FROM '.tablename('j_hmoney_recharge')." WHERE weid='{$_W['uniacid']}' $condition  and status=1 and usetype=1 ");
        $chargeback = pdo_fetch('SELECT COUNT(*) as num1,sum(cash) as fee1 FROM '.tablename('j_hmoney_recharge')." WHERE weid='{$_W['uniacid']}' $condition  and status=1 and usetype=2 ");
        $chargecount = pdo_fetchall("SELECT paytype,sum(cash) as fee1 FROM " . tablename('j_hmoney_recharge') . " WHERE weid='{$_W['uniacid']}' $condition and usetype=0 and  status=1 group by paytype");
        $chargelist=array();
        foreach($chargecount as $row){
            $chargelist[$row["paytype"]]=$row["fee1"];
        }
        $membercount = pdo_fetchcolumn("SELECT count(*) FROM " . tablename('j_hmoney_membercard') . " WHERE weid='{$_W['uniacid']}'  and createtime>='".$user['lasttime']."' and createtime<='".TIMESTAMP."' ");
        $memberallcount = pdo_fetchcolumn("SELECT count(*) FROM " . tablename('j_hmoney_membercard') . " WHERE weid='{$_W['uniacid']}'  ");
    }
    die(json_encode(array("success"=>true,"list"=>$list,"total"=>$total,"chargeitems"=>$chargeitems,"chargesale"=>$chargesale,"chargeback"=>$chargeback,"chargelist"=>$chargelist,"membercount"=>$membercount,"memberallcount"=>$memberallcount)));
	
} elseif ($operation == 'outputs') {
	$userlist = pdo_fetchall("SELECT id,realname FROM ".tablename('j_hmoney_user')." WHERE weid='{$_W['uniacid']}' and pcate='".$shopid."' order by id desc");
	$userary = array();
	foreach ($userlist as $row) {
		$userary[$row['id']]=$row['realname'];
	}
	$condition = " and groupid ='".$shopid."' ";
	switch(intval($_GPC['datetype'])){
		case "1":
			$condition .= " and createdate='".date('Y-m-d')."' ";
		break;
		case "2":
			$condition .= " and createdate='".date('Y-m-d',strtotime("-1 day"))."' ";
		break;
		case "3":
			$condition .= " and createdate>='".date('Y-m-d',strtotime("-6 day"))."' ";
		break;
		case "4":
			$condition .= " and createtime>='".strtotime($_GPC['statrtime'])."' and createtime<='".strtotime($_GPC['endtime'])."' ";
		break;
	}
	if($_GPC['keyword'])$condition .= " and (out_trade_no='".$_GPC['keyword']."') ";
	$list = pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_order')." WHERE weid='{$_W['uniacid']}' $condition order by id desc ");
	require_once "../framework/library/phpexcel/PHPExcel.php";
	$objPHPExcel = new PHPExcel();
	$objPHPExcel->getProperties()->setCreator("智慧收银台")
                               ->setLastModifiedBy("智慧收银台")
                               ->setTitle("数据EXCEL导出")
                               ->setSubject("数据EXCEL导出")
                               ->setDescription("备份数据")
                               ->setKeywords("excel")
                               ->setCategory("result file");
	//单号	消费对象	数量	订单金额	茶位	实付金额	优惠	支付方式	收银员	时间	状态	备注
	$excelAry=array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","X","T","U","V","W","X","Y","Z");
	$headerAry=array("编号","单号","消费对象","数量","总金额","优惠","实付","支付A","支付A金额","支付B","支付B金额","收银员","时间","状态","备注","店铺");
	for($i=0;$i<count($headerAry);$i++){
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue($excelAry[$i].'1',$headerAry[$i]);
	};
	$statusAry=array(
		0=>'挂单',
		1=>'下单',
		2=>'完成',
	);
	$num=2;
	foreach($list as $row){
		$objPHPExcel->setActiveSheetIndex(0)
			->setCellValue('A'.$num, "'".$row['out_trade_no'])
			->setCellValue('B'.$num, "'".$row['serialnum'])
			->setCellValue('C'.$num, intval($row['memberno']) ? '会员':'散客')
			->setCellValue('D'.$num, $row['num'])
			->setCellValue('E'.$num, $this->_2money($row['order_fee']))
			->setCellValue('F'.$num, $this->_2money($row['total_fee']))
			->setCellValue('G'.$num, $this->_2money($row['discount_fee']))
			->setCellValue('H'.$num, $row['ispay'] ? _getPaytpye($row['paytype']):"")
			->setCellValue('I'.$num, $this->_2money($row['paid_fee1']))
			->setCellValue('J'.$num, $row['ispay'] ? _getPaytpye($row['paytype2']):"")
			->setCellValue('K'.$num, $this->_2money($row['paid_fee2']))
			->setCellValue('L'.$num, $userary[$row['userid']])
			->setCellValue('M'.$num, date("Y/m/d H:i",$row['createtime']))
			->setCellValue('N'.$num, $statusAry[$row['status']])
			->setCellValue('O'.$num, $row['remark'])
			->setCellValue('P'.$num, $shop['companyname']);
		$num++;
	}
	$objPHPExcel->getActiveSheet()->setTitle('销售记录');
	$objPHPExcel->setActiveSheetIndex(0);
	ob_end_clean();
	header('Content-Type: application/vnd.ms-excel');
	header('Content-Disposition:attachment;filename="sale_temp.xls"');
	header('Cache-Control:max-age=0');
	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
	$objWriter->save('php://output');
	exit();
	
} elseif ($operation == 'outputs_detail') {
	$userlist = pdo_fetchall("SELECT id,realname FROM ".tablename('j_hmoney_user')." WHERE weid='{$_W['uniacid']}' and pcate='".$shopid."' order by id desc");
	$userary = array();
	foreach ($userlist as $row) {
		$userary[$row['id']]=$row['realname'];
	}
	$condition = " and groupid ='".$shopid."' ";
	switch(intval($_GPC['datetype'])){
		case "1":
			$condition .= " and createdate='".date('Y-m-d')."' ";
		break;
		case "2":
			$condition .= " and createdate='".date('Y-m-d',strtotime("-1 day"))."' ";
		break;
		case "3":
			$condition .= " and createdate>='".date('Y-m-d',strtotime("-6 day"))."' ";
		break;
		case "4":
			$condition .= " and createtime>='".strtotime($_GPC['statrtime'])."' and createtime<='".strtotime($_GPC['endtime'])."' ";
		break;
	}
	if($_GPC['keyword'])$condition .= " and (out_trade_no='".$_GPC['keyword']."') ";
	$list = pdo_fetchall("SELECT * FROM ".tablename('j_hmoney_ordergoods')." WHERE orderid in( SELECT id FROM ".tablename('j_hmoney_order')." WHERE weid='{$_W['uniacid']}' $condition ) order by id asc");
	
	require_once "../framework/library/phpexcel/PHPExcel.php";
	$objPHPExcel = new PHPExcel();
	$objPHPExcel->getProperties()->setCreator("智慧收银台")
                               ->setLastModifiedBy("智慧收银台")
                               ->setTitle("数据EXCEL导出")
                               ->setSubject("数据EXCEL导出")
                               ->setDescription("备份数据")
                               ->setKeywords("excel")
                               ->setCategory("result file");
	$objPHPExcel->setActiveSheetIndex(0)
				  ->setCellValue('A1',"单号")
				  ->setCellValue('B1',"条码")
				  ->setCellValue('C1',"品名")
				  ->setCellValue('D1',"原价")
				  ->setCellValue('E1',"销售价格")
				  ->setCellValue('F1',"数量")
				  ->setCellValue('G1',"金额")
				  ->setCellValue('H1',"属性")
				  ->setCellValue('I1',"支付状态")
				  ->setCellValue('J1',"状态")
				  ->setCellValue('K1',"时间")
				  ->setCellValue('L1',"店铺");
	$statusary=array(
		"0"=>"",
		"1"=>"下单",
		"2"=>"完成",
	);
	$orderGoodsPay=array(
		"0"=>"未付款",
		"1"=>"已付款",
		"2"=>"",
		"3"=>"部分退款",
		"4"=>"全部退款",
	);
	$num=2;
	foreach($list as $row){
		
		$objPHPExcel->setActiveSheetIndex(0)
				  ->setCellValue('A'.$num, "'".$row['out_trade_no'])
				  ->setCellValue('B'.$num, "'".$row['goodsn'])
				  ->setCellValue('C'.$num, $row['title'])
				  ->setCellValue('D'.$num, $row['oldprice'])
				  ->setCellValue('E'.$num, $row['price'])
				  ->setCellValue('F'.$num, $row['num'])
				  ->setCellValue('G'.$num, $this->_2money($row['total_fee']))
				  ->setCellValue('H'.$num, $row['taste'])
				  ->setCellValue('I'.$num, $orderGoodsPay[$row['ispay']])
				  ->setCellValue('J'.$num, $statusary[$row['status']])
				  ->setCellValue('K'.$num, date("Y/m/d H:i",$row['createtime']))
				  ->setCellValue('L'.$num, $shop['companyname']);
		$num++;
	}
	
	$objPHPExcel->getActiveSheet()->setTitle('商品销售记录');
	$objPHPExcel->setActiveSheetIndex(0);
	ob_end_clean();
	header('Content-Type: application/vnd.ms-excel');
	header('Content-Disposition:attachment;filename="salegoods_temp.xls"');
	header('Cache-Control:max-age=0');
	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
	$objWriter->save('php://output');
	exit();
	
} elseif ($operation == 'outputc') {
	$userlist = pdo_fetchall("SELECT id,realname FROM ".tablename('j_hmoney_user')." WHERE weid='{$_W['uniacid']}' and pcate='".$shopid."' order by id desc");
	$userary = array();
	foreach ($userlist as $row) {
		$userary[$row['id']]=$row['realname'];
	}
	$condition = " and a.groupid ='".$shopid."' ";
	switch(intval($_GPC['datetype'])){
		case "1":
			$condition .= " and a.createdate='".date('Y-m-d')."' ";
		break;
		case "2":
			$condition .= " and a.createdate='".date('Y-m-d',strtotime("-1 day"))."' ";
		break;
		case "3":
			$condition .= " and a.createdate>='".date('Y-m-d',strtotime("-6 day"))."' ";
		break;
		case "4":
			$condition .= " and a.createtime>='".strtotime($_GPC['statrtime'])."' and a.createtime<='".strtotime($_GPC['endtime'])."' ";
		break;
	}
	if($_GPC['keyword']){
		$mid = pdo_fetchcolumn('SELECT id FROM '.tablename('j_hmoney_membercard')."  WHERE weid='{$_W['uniacid']}' and cardno='".$_GPC['keyword']."' limit 1");
		$condition .= " and (a.cid='".$mid."') ";
	}
	$sql="SELECT a.*,b.cardno,b.realname FROM " . tablename('j_hmoney_recharge') . " a left join ".tablename('j_hmoney_membercard')." b on a.cid=b.id WHERE a.weid='{$_W['uniacid']}' $condition order by a.id desc  ";
	$list = pdo_fetchall($sql);
	require_once "../framework/library/phpexcel/PHPExcel.php";
	$objPHPExcel = new PHPExcel();
	$objPHPExcel->getProperties()->setCreator("智慧收银台")
                               ->setLastModifiedBy("智慧收银台")
                               ->setTitle("数据EXCEL导出")
                               ->setSubject("数据EXCEL导出")
                               ->setDescription("备份数据")
                               ->setKeywords("excel")
                               ->setCategory("result file");

	$objPHPExcel->setActiveSheetIndex(0)
				  ->setCellValue('A1',"卡号")
				  ->setCellValue('B1',"操作")
				  ->setCellValue('C1',"支付方式")
				  ->setCellValue('D1',"操作人")
				  ->setCellValue('E1',"操作金额")
				  ->setCellValue('F1',"赠送金额")
				  ->setCellValue('G1',"变动前金额")
				  ->setCellValue('H1',"变动后金额")
				  ->setCellValue('I1',"时间")
				  ->setCellValue('J1',"状态")
				  ->setCellValue('K1',"备注")
				  ->setCellValue('L1',"店铺");
	$doType=array(
		0=>"充值",
		1=>"消费",
		2=>"退还",
	);
	$paytype=array(
		"0"=>"微信",
		"1"=>"支付宝",
		"2"=>"现金",
		"3"=>"银行卡",
		"-1"=>"-",
	);
	$num=2;
	foreach($list as $row){
		
		$objPHPExcel->setActiveSheetIndex(0)
				  ->setCellValue('A'.$num, "'".$row['cardno'])    
				  ->setCellValue('B'.$num, $doType[$row['usetype']])
				  ->setCellValue('C'.$num, $paytype[$row['paytype']])
				  ->setCellValue('D'.$num, $userary[$row['userid']] ? $userary[$row['userid']] : "后台")
				  ->setCellValue('E'.$num, $this->_2money($row['cash']))
				  ->setCellValue('F'.$num, $this->_2money($row['gift']))
				  ->setCellValue('G'.$num, $this->_2money($row['startfee']))
				  ->setCellValue('H'.$num, $this->_2money($row['endfee']))
				  ->setCellValue('I'.$num, date("Y/m/d H:i",$row['createtime']))
				  ->setCellValue('J'.$num, $row['status'] ? "成功":"失败")
				  ->setCellValue('K'.$num, $row['remark'])
				  ->setCellValue('L'.$num, $shop['companyname']);;
		$num++;
	}
	
	$objPHPExcel->getActiveSheet()->setTitle('充值记录');
	$objPHPExcel->setActiveSheetIndex(0);
	ob_end_clean();
	header('Content-Type: application/vnd.ms-excel');
	header('Content-Disposition:attachment;filename="charge_temp.xls"');
	header('Cache-Control:max-age=0');
	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
	$objWriter->save('php://output');
	exit();
	
}
include $this->template('web/'.$cfg['floder'].'/sale');